﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;

using System.Collections.Generic;
using Yipusoft.Common.Model;
using Yipusoft.TownshipEnterprise.Model;
using Yipusoft.Common.BLL;
using Yipusoft.TownshipEnterprise.BLL;
using System.IO;
using System.Drawing;
using Yipusoft.Account.BLL;
using System.Drawing.Imaging;
using Yipusoft.Account.Model;

public partial class TownshipEnterprise_SoldierAdd : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            //绑定民族
            BindNation();
            BindDuty();     //绑定职务
            BindRank();     //绑定警衔
            BindSpeciality();       //绑定专业1
            BindProvince();     //绑定籍贯
            BindBackground();       //绑定家庭出身
            BindCulture();      //绑定文化程度
            BindReligion();     //绑定宗教信仰
            BindStatus();       //绑定本人成分
            BindCities(ddlProvinces.SelectedValue);     //绑定 籍贯
            BindSpeciality(ddlSpeciality1.SelectedValue);   //绑定专业2
            BindPolitical();        //绑定政治面貌
            BindHobby();        //绑定特长

            if (String.IsNullOrEmpty(Request["ID"]))
                BindDepartment("203001", "203002", "203003");
            else
                BindDepartment("203001", "203004", "203005");

            //if (ddlSection.Items.Count == 0)
            //{
            //    Response.Write("<script>alert('没有权限！');history.back(0);</script>");
            //    return;
            //}
            BindSoldiers();
            if (!String.IsNullOrEmpty(Request["ID"]))
            {
                //if (!(Yipusoft.Account.BLL.User.HasPermission(Context.User.Identity.Name, "203001") || Yipusoft.Account.BLL.User.HasPermission(Context.User.Identity.Name, "203004") || Yipusoft.Account.BLL.User.HasPermission(Context.User.Identity.Name, "203005")))
                //{
                //    Response.Write("<script>alert('没有权限！');history.back(0);</script>");
                //    return;
                //}
                btnSave.Visible = false;
                btnUpdate.Visible = true;
                ActionTitle.Text = "更新士兵档案";

                BindSoldier(Request["ID"]);

                //if (IsContract.Checked)
                //{
                //    Newillpanel.Visible = false;
                //}
                //else
                //{
                //    Newillpanel.Visible = true;
                //}
            }


        }
    }

    /// <summary>
    /// 绑定政治面貌
    /// </summary>
    private void BindPolitical()
    {
        ListItem blankLI = new ListItem("", "");
        ddlPolitical.Items.Add(blankLI);
        foreach (CodeItemInfo item in CodeItem.GetList("ParentID='ZZMM00' ORDER BY SeqID"))
        {
            ListItem li = new ListItem(item.ItemName, item.ItemID);
            ddlPolitical.Items.Add(li);
        }
    }

    /// <summary>
    /// 绑定特长
    /// </summary>
    private void BindHobby()
    {
        ListItem blankLI = new ListItem("", "");
        ddlHobby.Items.Add(blankLI);
        foreach (CodeItemInfo item in CodeItem.GetList("ParentID='XQAH00' ORDER BY SeqID"))
        {
            ListItem li = new ListItem(item.ItemName, item.ItemID);
            ddlHobby.Items.Add(li);
        }
    }

    /// <summary>
    /// 页面赋值
    /// </summary>
    /// <param name="soldierID"></param>
    private void BindSoldier(string soldierID)
    {

        TownSoldiersInfo soldierInfo = TownSoldiers.GetTownSoldiers(new Guid(soldierID));
        SoldierName.Text = soldierInfo.SoldierName;
        ddlSex.SelectedValue = soldierInfo.Sex.Trim().ToString();
        ddlBackground.SelectedValue = soldierInfo.Background;
        Birthday.Text = soldierInfo.Birth == DateTime.MinValue ? "" : soldierInfo.Birth.ToString("yyyy-MM-dd");
        CardID.Text = soldierInfo.CardID;
        ChooseID.Text = soldierInfo.ChooseID;
        ConfirmID.Text = soldierInfo.ConfirmID;
        ddlCulture.SelectedValue = soldierInfo.Culture;
        //ListItem listItem=new ListItem(soldierInfo.DepartmentName,soldierInfo.DepartmentID);
        //ListItemCollection departments=ddlDepartment.Items;
        bool isexist = false;
        ddlDepartment.SelectedValue =TownBasic.GetTownBasic(soldierInfo.TownBasicID).DepartmentID.ToString().Substring(0, 4) + "000";
        DepartmentListBind();

        //for (int i = 0; i < ddlSection.Items.Count; i++)
        //{
        //    if (ddlSection.Items[i].Value.Trim() == soldierInfo.DepartmentID.Trim())
        //    {
        //        isexist = true;
        //    }
        //}
        ddlSection.SelectedValue = TownBasic.GetTownBasic(soldierInfo.TownBasicID).DepartmentID.ToString();
        BingDDLBasicInfo();


        //ddlSection.SelectedValue = soldierInfo.DepartmentID.Trim();
        ddlDuty.SelectedValue = soldierInfo.Duty;
        Height.Text = soldierInfo.Height == 0 ? "" : soldierInfo.Height.ToString();
        HomePlace.Text = soldierInfo.HomePlace;
        //soldierInfo.IsContract = false;
        JoinPlace.Text = soldierInfo.JoinPlace;
        JoinDate.Text = soldierInfo.JoinTime == DateTime.MinValue ? "" : soldierInfo.JoinTime.ToString("yyyy-MM-dd");
        ddlMerriage.SelectedValue = soldierInfo.Marriage;
        ddlNation.SelectedValue = soldierInfo.Nation;
        if (soldierInfo.Nation != "")
        {
            ddlProvinces.SelectedValue = CodeItem.GetCodeItem(soldierInfo.Nation).ItemLevel <= 2 ? CodeItem.GetCodeItem(soldierInfo.Nation).ParentID : CodeItem.GetCodeItem(CodeItem.GetCodeItem(soldierInfo.Nation).ParentID).ParentID;
        }
        BindCities(ddlProvinces.SelectedValue);
        if (soldierInfo.Native != null && soldierInfo.Native != "")
        {
            CodeItemInfo Nation = CodeItem.GetCodeItem(soldierInfo.Native);
            if (Nation.ItemLevel == 2)
            {
                ddlProvinces.SelectedValue = Nation.ParentID;

            }
            else if (Nation.ItemLevel == 3)
            {
                ddlProvinces.SelectedValue = CodeItem.GetCodeItem(Nation.ParentID).ParentID;
            }
            BindCities(ddlProvinces.SelectedValue);
            ddlCities.SelectedValue = soldierInfo.Native;
        }

        PartyDate.Text = soldierInfo.PartyTime == DateTime.MinValue ? "" : soldierInfo.PartyTime.ToString("yyyy-MM-dd");
        ddlRank.SelectedValue = soldierInfo.Rank;
        RegisterID.Text = soldierInfo.RegisterID;
        ddlReligion.SelectedValue = soldierInfo.Religion;


        ddlSpeciality1.SelectedValue = soldierInfo.Speciality1;

        BindSpeciality(ddlSpeciality1.SelectedValue);

        ddlSpeciality2.SelectedValue = soldierInfo.Speciality2;
        ddlStatus.SelectedValue = soldierInfo.Status;
        Weight.Text = soldierInfo.Weight == 0.0m ? "" : soldierInfo.Weight.ToString();
        YouthDate.Text = soldierInfo.YouthTime == DateTime.MinValue ? "" : soldierInfo.YouthTime.ToString("yyyy-MM-dd");
        IsContract.Checked = soldierInfo.IsContract;


        ddlPolitical.SelectedValue = soldierInfo.Political;
        ddlHobby.SelectedValue = soldierInfo.Hobby;
        SGRegNO.Text = soldierInfo.SGRegNO;
        SGGegDate.Text = soldierInfo.SGGegDate == DateTime.MinValue ? "" : soldierInfo.SGGegDate.ToString("yyyy-MM-dd");
        Training.Text= soldierInfo.Training ;
        Reward.Text= soldierInfo.Reward ;
        Resume.Text=soldierInfo.Resume ;
        Remark.Text=soldierInfo.Remark ;


        
    }

    /// <summary>
    /// 绑定显示士兵信息
    /// </summary>
    private void BindSoldiers()
    {
        
        List<TownSoldiersInfo> lstts = TownSoldiers.GetList("settime", "desc", "IsDelete=0  and setTime>='" + DateTime.Today + "' and SetAID='" + User.Identity.Name + "'", 20, 0);
       
        foreach (TownSoldiersInfo info in lstts)
        {
            info.Rank = CodeItem.GetCodeItem(info.Rank).ItemName;
            info.Native = CodeItem.GetCodeItem(info.Native).ItemName;
            info.TownBasicArmy = TownBasic.GetTownBasic(info.TownBasicID).Army;
        }

        gvSoldiers.DataSource = lstts;
        gvSoldiers.DataBind();
    }

    private void InitDate()
    {
        SoldierName.Text = "";
        ddlSex.SelectedIndex = 0;
        ddlBackground.SelectedIndex = 0;
        Birthday.Text = "";
        CardID.Text = "";
        ChooseID.Text = "";
        ConfirmID.Text = "";
        ddlCulture.SelectedIndex = 0;
        ddlDepartment.SelectedIndex = 0;
        ddlDuty.SelectedIndex = 0;
        Height.Text = "";
        HomePlace.Text = "";
        //soldierInfo.IsContract = false;
        JoinPlace.Text = "";
        JoinDate.Text = "";
        ddlMerriage.SelectedIndex = 0;
        ddlNation.SelectedIndex = 0;
        ddlProvinces.SelectedIndex = 0;
        BindCities(ddlProvinces.SelectedValue);
        //ddlCities.SelectedValue = soldierInfo.Nation;
        ////soldierInfo.Native = ddlCities.SelectedValue;
        PartyDate.Text = "";
        ddlRank.SelectedIndex = 0;
        RegisterID.Text = "";
        ddlReligion.SelectedIndex = 0;


        ddlSpeciality1.SelectedIndex = 0;
        ////soldierInfo.Speciality2 = ddlSpeciality2.SelectedValue;
        BindSpeciality(ddlSpeciality1.SelectedValue);
        ddlStatus.SelectedIndex = 0;
        Height.Text = "";
        Weight.Text = "";
        YouthDate.Text = "";

        ddlPolitical.SelectedIndex = 0;
        ddlHobby.SelectedIndex = 0;
    }

    /// <summary>
    /// 绑定民族
    /// </summary>
    private void BindNation()
    {
        ListItem blankLI = new ListItem("", "");
        ddlNation.Items.Add(blankLI);
        foreach (CodeItemInfo item in CodeItem.GetList("ParentID='MZ00' ORDER BY SeqID"))
        {
            ListItem li = new ListItem(item.ItemName, item.ItemID);
            ddlNation.Items.Add(li);
        }
        //ddlNation.DataSource = CodeItem.GetList("ParentID='MZ00' ORDER BY SeqID"); 
        //ddlNation.DataTextField = "ItemName";
        //ddlNation.DataValueField = "ItemID";
        //ddlNation.DataBind();
        //BindStatus();
    }

    /// <summary>
    /// 绑定职务
    /// </summary>
    private void BindDuty()
    {
        //ddlDuty.DataSource = CodeItem.GetList("ParentID='SBZW00' ORDER BY SeqID");
        //ddlDuty.DataTextField = "ItemName";
        //ddlDuty.DataValueField = "ItemID";
        //ddlDuty.DataBind();
        ListItem blankLI = new ListItem("", "");
        ddlDuty.Items.Add(blankLI);
        foreach (CodeItemInfo item in CodeItem.GetList("ParentID='SBZW00' ORDER BY SeqID"))
        {
            ListItem li = new ListItem(item.ItemName, item.ItemID);
            ddlDuty.Items.Add(li);
        }
    }

    /// <summary>
    /// 绑定警衔
    /// </summary>
    private void BindRank()
    {
        //ddlRank.DataSource = CodeItem.GetList("ParentID='SBJX00' ORDER BY SeqID");
        //ddlRank.DataTextField = "ItemName";
        //ddlRank.DataValueField = "ItemID";
        //ddlRank.DataBind();
        ListItem blankLI = new ListItem("", "");
        ddlRank.Items.Add(blankLI);
        foreach (CodeItemInfo item in CodeItem.GetList("ParentID='SBJX00' ORDER BY SeqID"))
        {
            ListItem li = new ListItem(item.ItemName, item.ItemID);
            ddlRank.Items.Add(li);
        }
    }

    /// <summary>
    /// 绑定专业
    /// </summary>
    private void BindSpeciality()
    {
        //ddlSpeciality1.DataSource = CodeItem.GetList("ParentID='ZY0000' ORDER BY SeqID");
        //ddlSpeciality1.DataTextField = "ItemName";
        //ddlSpeciality1.DataValueField = "ItemID";
        //ddlSpeciality1.DataBind();
        ListItem blankLI = new ListItem("", "");
        ddlSpeciality1.Items.Add(blankLI);
        foreach (CodeItemInfo item in CodeItem.GetList("ParentID='ZY0000' ORDER BY SeqID"))
        {
            ListItem li = new ListItem(item.ItemName, item.ItemID);
            ddlSpeciality1.Items.Add(li);
        }
    }

    /// <summary>
    /// 绑定籍贯
    /// </summary>
    private void BindProvince()
    {
        //ddlProvinces.DataSource = CodeItem.GetList("ParentID='SS000000' ORDER BY SeqID");
        //ddlProvinces.DataTextField = "ItemName";
        //ddlProvinces.DataValueField = "ItemID";
        //ddlProvinces.DataBind();
        ListItem blankLI = new ListItem("", "");
        ddlProvinces.Items.Add(blankLI);
        foreach (CodeItemInfo item in CodeItem.GetList("ParentID='SS000000' ORDER BY SeqID"))
        {
            ListItem li = new ListItem(item.ItemName, item.ItemID);
            ddlProvinces.Items.Add(li);
        }
    }
    /// <summary>
    /// 绑定家庭出身
    /// </summary>
    private void BindBackground()
    {
        //ddlBackground.DataSource = CodeItem.GetList("ParentID='JTCS00' ORDER BY SeqID");
        //ddlBackground.DataTextField = "ItemName";
        //ddlBackground.DataValueField = "ItemID";
        //ddlBackground.DataBind();
        ListItem blankLI = new ListItem("", "");
        ddlBackground.Items.Add(blankLI);
        foreach (CodeItemInfo item in CodeItem.GetList("ParentID='JTCS00' ORDER BY SeqID"))
        {
            ListItem li = new ListItem(item.ItemName, item.ItemID);
            ddlBackground.Items.Add(li);
        }
    }
    /// <summary>
    /// 绑定本人成分
    /// </summary>
    private void BindStatus()
    {
        //ddlStatus.DataSource = CodeItem.GetList("ParentID='SBBRCF00' ORDER BY SeqID");
        //ddlStatus.DataTextField = "ItemName";
        //ddlStatus.DataValueField = "ItemID";
        //ddlStatus.DataBind();
        ListItem blankLI = new ListItem("", "");
        ddlStatus.Items.Add(blankLI);
        foreach (CodeItemInfo item in CodeItem.GetList("ParentID='SBBRCF00' ORDER BY SeqID"))
        {
            ListItem li = new ListItem(item.ItemName, item.ItemID);
            ddlStatus.Items.Add(li);
        }
    }
    /// <summary>
    /// 绑定文化程度
    /// </summary>
    private void BindCulture()
    {
        //ddlCulture.DataSource = CodeItem.GetList("ParentID='WHCD00' ORDER BY SeqID");
        //ddlCulture.DataTextField = "ItemName";
        //ddlCulture.DataValueField = "ItemID";
        //ddlCulture.DataBind();
        ListItem blankLI = new ListItem("", "");
        ddlCulture.Items.Add(blankLI);
        foreach (CodeItemInfo item in CodeItem.GetList("ParentID='WHCD00' ORDER BY SeqID"))
        {
            ListItem li = new ListItem(item.ItemName, item.ItemID);
            ddlCulture.Items.Add(li);
        }
    }
    /// <summary>
    /// 绑定宗教信仰
    /// </summary>
    private void BindReligion()
    {
        //ddlReligion.DataSource = CodeItem.GetList("ParentID='ZJXY00' ORDER BY SeqID");
        //ddlReligion.DataTextField = "ItemName";
        //ddlReligion.DataValueField = "ItemID";
        //ddlReligion.DataBind();
        ListItem blankLI = new ListItem("", "");
        ddlReligion.Items.Add(blankLI);
        foreach (CodeItemInfo item in CodeItem.GetList("ParentID='ZJXY00' ORDER BY SeqID"))
        {
            ListItem li = new ListItem(item.ItemName, item.ItemID);
            ddlReligion.Items.Add(li);
        }
    }
    protected void ddlProvinces_SelectedIndexChanged(object sender, EventArgs e)
    {
        BindCities(ddlProvinces.SelectedValue);
    }

    private void BindCities(string province)
    {
        //ddlCities.DataSource = CodeItem.GetList("ParentID='"+province+"' Order by SeqID");
        //ddlCities.DataTextField = "ItemName";
        //ddlCities.DataValueField = "ItemID";
        //ddlCities.DataBind();
        ddlCities.Items.Clear();
        if (province.Trim() == "")
        {
            ListItem blankLI = new ListItem("", "");
            ddlCities.Items.Add(blankLI);
        }
        else
        {
            foreach (CodeItemInfo item in CodeItem.GetList("ParentID='" + province + "' Order by SeqID"))
            {
                ListItem li = new ListItem(item.ItemName, item.ItemID);
                ddlCities.Items.Add(li);
                foreach (CodeItemInfo subItem in CodeItem.GetList("ParentID='" + item.ItemID + "' Order by SeqID"))
                    ddlCities.Items.Add(new ListItem("\u3000" + subItem.ItemName, subItem.ItemID));
            }
        }
    }
    protected void ddlSpeciality1_SelectedIndexChanged(object sender, EventArgs e)
    {
        BindSpeciality(ddlSpeciality1.SelectedValue);
    }

    private void BindSpeciality(string speciality)
    {
        ddlSpeciality2.Items.Clear();
        if (speciality.Trim() == "")
        {
            ListItem blankLI = new ListItem("", "");
            ddlSpeciality2.Items.Add(blankLI);
        }
        else
        {
            ddlSpeciality2.DataSource = CodeItem.GetList("ParentID='" + speciality + "' Order by SeqID");
            ddlSpeciality2.DataTextField = "ItemName";
            ddlSpeciality2.DataValueField = "ItemID";
            ddlSpeciality2.DataBind();
        }
    }

    private void BindDepartment(string permissionAdmin, string permissionLevel, string permissionUnit)
    {
        UserInfo userInfo = Yipusoft.Account.BLL.User.GetUser(User.Identity.Name);
        DepartmentInfo department = Department.GetDepartment(userInfo.DepartmentID);
        string departmentID = Yipusoft.Account.BLL.User.GetUser(User.Identity.Name).DepartmentID;
        //ddlDepartment.DataSource = Department.GetList(" DepartmentId like '%000' or departmentId ='1312100' or departmentId='1313100'");
        //ddlDepartment.DataBind();


        //UserInfo userInfo = Yipusoft.Account.BLL.User.GetUser(User.Identity.Name);
        DepartmentInfo departmentIDs = Department.GetDepartment(userInfo.DepartmentID);
        if (userInfo.DepartmentID.Substring(0, 4) == "1300")
        {
            ddlDepartment.DataSource = Yipusoft.Account.BLL.Department.GetList(" (SUBSTRING(DepartmentID, 5, 3) = '000') and DepartmentID<>'1300000' ");
            ddlDepartment.DataBind();
            DepartmentListBind();
        }
        else
        {
            ddlDepartment.DataSource = Yipusoft.Account.BLL.Department.GetList(" DepartmentID= '" + departmentIDs.DepartmentID.Substring(0, 4) + "000' ");
            ddlDepartment.DataBind();
            DepartmentListBind();
        }



        if (Yipusoft.Account.BLL.User.HasPermission(Context.User.Identity.Name, permissionAdmin))
        {
            BingDDLBasicInfo();
        }
        else if (Yipusoft.Account.BLL.User.HasPermission(Context.User.Identity.Name, permissionLevel))
        {
            if (departmentID.Substring(0, 5) == "13121")
            {
                ddlDepartment.SelectedValue = departmentID;
            }
            else
                if (departmentID == "1313100")
                {
                    ddlDepartment.SelectedValue = departmentID;
                }
                else
                {
                    ddlDepartment.SelectedValue = departmentID.Substring(0, 4) + "000";
                }
            ddlDepartment.Enabled = false;
            BingDDLBasicInfo();
        }
        else
            if (Yipusoft.Account.BLL.User.HasPermission(Context.User.Identity.Name, permissionUnit))
            {
                ddlDepartment.SelectedValue = departmentID.Substring(0, 4) + "000";
                ddlDepartment.Enabled = false;
                BingDDLBasicInfo();
                ddlSection.SelectedValue = departmentID;
                ddlSection.Enabled = false;
            }

    }

    /// <summary>
    /// 绑定县
    /// </summary>
    void DepartmentListBind()
    {
        ddlSection.Items.Clear();
        string strWhere = "DepartmentID like '" + ddlDepartment.SelectedValue.Substring(0, 4) + "2%' and   SUBSTRING(DepartmentID, 5, 1)<>'0' ";
        List<DepartmentInfo> list = Department.GetList(strWhere);
        foreach (DepartmentInfo dpt in list)
        {
            dpt.ShortName = dpt.ShortName.Replace("消防科", "");
            dpt.ShortName = dpt.ShortName.Replace("大队", "");
            dpt.ShortName = dpt.ShortName.Replace("消防", "");
        }
        ddlSection.DataSource = list;
        ddlSection.DataBind();
        BingDDLBasicInfo();
    }

    /// <summary>
    /// 绑定消防队
    /// </summary>
    void BingDDLBasicInfo()
    {
        ddlTownBasic.Items.Clear();
        string strWhere = " DepartmentID='" + ddlSection.SelectedValue.ToString() + "'";
        List<TownBasicInfo> list = TownBasic.GetList(strWhere);
        if (list.Count == 0)
        {
            btnSave.Enabled = false;
            lblInfo.Text = "错误：没有可添加信息的消防队，请先添加此地区消防队。";
            ddlTownBasic.Items.Add("此地区没有消防队");

            string colorStr = System.Drawing.ColorTranslator.ToHtml(Color.Red);
            ddlTownBasic.Items[0].Attributes.Add("style", "color:" + colorStr);

            return;
        }
        else
        {
            btnSave.Enabled = true;
            lblInfo.Text = "";
            ddlTownBasic.DataSource = list;
            ddlTownBasic.DataBind();
        }
    }

    private List<Yipusoft.Account.Model.DepartmentInfo> GetDepartmentList(string departmentID, string permissionAdmin, string permissionLevel, string permissionUnit)
    {
        List<DepartmentInfo> departmentList = new List<DepartmentInfo>();
        if (Yipusoft.Account.BLL.User.HasPermission(Context.User.Identity.Name, permissionAdmin))
            departmentList = Department.GetList("1=1");
        else

            if (Yipusoft.Account.BLL.User.HasPermission(Context.User.Identity.Name, permissionLevel))
                departmentList = Department.GetList("DepartmentID like '" + departmentID.Substring(0, 4) + "%'");
            else
                if (Yipusoft.Account.BLL.User.HasPermission(Context.User.Identity.Name, permissionUnit))
                    departmentList = Department.GetList("DepartmentID='" + departmentID + "'");

        return departmentList;
    }
    protected void btnSave_Click(object sender, EventArgs e)
    {
        save(new Guid(),true);
    }

    private void save(Guid id,bool isAdd)
    {
        TownSoldiersInfo soldierInfo = new TownSoldiersInfo();
        soldierInfo.SoldierID = id;

        HttpFileCollection files = HttpContext.Current.Request.Files;
        HttpPostedFile file = files.Get("ctl00$ContentPlaceHolder1$fileUpload");
        string path = string.Empty;
        string picName = DateTime.Now.ToString("yyyyMMddHHmmssff");

        bool img = false;
        bool isload = false;
        if (file.ContentLength == 0)
        {
            img = true;
            isload = false;
        }
        else
        {
            img = SaveImg(picName, "1", file, out path);
            isload = true;
        }
        if (!img)
        {
            Response.Write("<script language=javascript>alert('图片格式不正确，请上传 *.bmp,*.jpg,*.jpeg 格式图片')</script>");
            return;
        }
        //图片信息保存到数据库
        else
        {
            try
            {
                if (!isload)
                {
                    soldierInfo.Picture = TownSoldiers.GetTownSoldiers(id).Picture;
                    goto ok;
                }
                TownPicsInfo pic = new TownPicsInfo();
                pic.id = Guid.NewGuid();
                pic.TownBasicInfoID = soldierInfo.SoldierID;
                pic.TownPicstypeID = "v";
                pic.TownItemsID = "1";
                pic.PicPath = path;
                //pic.PicDescript = txtPhotoDetails.Text;

                bool b = TownPics.Insert(pic);

                if (b)
                {
                    Response.Write("<script language=javascript>alert('保存成功！')</script>");
                    soldierInfo.Picture = path;
                    //BindDateList(ViewState["TownBasicID"].ToString());
                    goto ok;
                }
                else
                {
                    //从硬盘删除图片文件
                    string allPath = Request.MapPath("") + path;
                    try
                    {
                        File.Delete(allPath);

                    }
                    catch
                    { }
                }
            }
            catch
            {
                string allPath = Request.MapPath("") + path;
                try
                {
                    File.Delete(allPath);
                }
                catch
                { }
            }
            Response.Write("<script language=javascript>alert('保存失败，请重新上传！')</script>");
            return;
        }
    ok:

        
        AssignSoldierInfo(soldierInfo);




        bool bo = false;
        if (isAdd)
            bo = TownSoldiers.Insert(soldierInfo);
        else
            bo = TownSoldiers.Update(soldierInfo);
        if (bo)
        {
            lblInfo.ForeColor = Color.Black;
            lblInfo.Text = "保存成功";
            BindSoldiers();     //显示士兵信息
            InitDate();     //清空文本框
        }
        else
        {
            lblInfo.ForeColor = Color.Red;
            lblInfo.Text = "保存失败！";
        }
    }

    private void AssignSoldierInfo(TownSoldiersInfo soldierInfo)
    {
        soldierInfo.Background = ddlBackground.SelectedValue;
        soldierInfo.Birth = Birthday.Text == "" ? DateTime.MinValue : Convert.ToDateTime(Birthday.Text);
        soldierInfo.CardID = CardID.Text;
        soldierInfo.ChooseID = ChooseID.Text;
        soldierInfo.ConfirmID = ConfirmID.Text;
        soldierInfo.Culture = ddlCulture.SelectedValue;
        soldierInfo.TownBasicID =new Guid(ddlTownBasic.SelectedValue);
        soldierInfo.Duty = ddlDuty.SelectedValue;
        soldierInfo.Height = Height.Text == "" ? 0 : int.Parse(Height.Text);
        soldierInfo.HomePlace = HomePlace.Text;
        soldierInfo.JoinPlace = JoinPlace.Text;
        soldierInfo.JoinTime = JoinDate.Text == "" ? DateTime.MinValue : Convert.ToDateTime(JoinDate.Text);
        soldierInfo.Marriage = ddlMerriage.SelectedValue;
        soldierInfo.Nation = ddlNation.SelectedValue;
        soldierInfo.Native = ddlCities.SelectedValue;
        soldierInfo.PartyTime = PartyDate.Text == "" ? DateTime.MinValue : Convert.ToDateTime(PartyDate.Text);
        soldierInfo.Rank = ddlRank.SelectedValue;
        soldierInfo.RegisterID = RegisterID.Text;
        soldierInfo.Religion = ddlReligion.SelectedValue;
        soldierInfo.Sex = ddlSex.SelectedValue;
        string Name = SoldierName.Text;
        Name = Name.Replace(" ", "");
        soldierInfo.SoldierName = Name;
        soldierInfo.Speciality1 = ddlSpeciality1.SelectedValue;
        soldierInfo.Speciality2 = ddlSpeciality2.SelectedValue;
        soldierInfo.Status = ddlStatus.SelectedValue;
        soldierInfo.Weight = Weight.Text == "" ? 0 : Convert.ToDecimal(Weight.Text);
        soldierInfo.YouthTime = YouthDate.Text == "" ? DateTime.MinValue : Convert.ToDateTime(YouthDate.Text);
        soldierInfo.IsContract = IsContract.Checked;

        //新
        soldierInfo.Hobby = ddlHobby.SelectedValue;
        soldierInfo.Political = ddlPolitical.SelectedValue;

        //新二
        soldierInfo.SGRegNO = SGRegNO.Text;
        soldierInfo.SGGegDate = SGGegDate.Text == "" ? DateTime.MaxValue : Convert.ToDateTime(SGGegDate.Text);
        soldierInfo.Training = UserFun.TextToHtml(Training.Text);
        soldierInfo.Reward = UserFun.TextToHtml(Reward.Text);
        soldierInfo.Resume = UserFun.TextToHtml(Resume.Text);
        soldierInfo.Remark = UserFun.TextToHtml(Remark.Text);

        //
        soldierInfo.SetAID = User.Identity.Name;
        soldierInfo.SetUserName = Yipusoft.Account.BLL.User.GetUser(User.Identity.Name).UserName;
        soldierInfo.SetTime = DateTime.Now;
        soldierInfo.TurnInDate = DateTime.Now;
        soldierInfo.DeleteDate = DateTime.Now;
        
    }

    /// <summary>
    /// 上传头像
    /// </summary>
    /// <param name="limitWidth"></param>
    /// <param name="limitHeight"></param>
    /// <returns>
    /// %：不支持的上传文件类型
    /// -：超过规定的尺寸
    /// #：上传文件出错
    /// </returns>
    private string UploadPhoto(int limitWidth, int limitHeight)
    {
        string ret = "";
        if (fileUpload.PostedFile != null && fileUpload.PostedFile.ContentLength > 0)
        {
            try
            {
                // if not already present, create a directory named /Uploads/<CurrentUserName>
                string filename = fileUpload.FileName.ToLower();
                int i = filename.LastIndexOf(".");
                filename = filename.Substring(i, filename.Length - i);

                if (!(filename == ".jpg" || filename == ".jpeg" || filename == ".gif" || filename == ".png" || filename == ".bmp"))
                {
                    ret = "%";

                }//检查上传文件的格式是否有效
                else
                {
                    Stream oStream = fileUpload.PostedFile.InputStream;
                    System.Drawing.Image oImage = System.Drawing.Image.FromStream(oStream);

                    int owidth = oImage.Width; //原图宽度
                    int oheight = oImage.Height; //原图高度

                    if (owidth > limitWidth || oheight > limitHeight)
                    {
                        ret = "-";

                    }//检查是否超出规定尺寸
                    else
                    {
                        string dirUrl = this.Request.ApplicationPath +
                           "/Uploads/" + this.Page.User.Identity.Name;
                        string dirPath = Server.MapPath(dirUrl);
                        if (!Directory.Exists(dirPath))
                            Directory.CreateDirectory(dirPath);
                        // save the file under the user's personal folder
                        string fileUrl = dirUrl + "/" + DateTime.Now.ToString("yyMMddHHmmss") + filename;
                        fileUpload.PostedFile.SaveAs(Server.MapPath(fileUrl));
                        //Profile.Initialize(this.Page.User.Identity.Name, true);
                        ret = fileUrl;
                    }
                }
            }
            catch
            {
                ret = "#";
            }
        }
        return ret;
    }


    /// <summary>
    /// 上传图片
    /// </summary>
    /// <param name="name1">图片名称，不包含扩展名</param>
    /// <param name="typepath">图片分类目录TownItems表id</param>
    /// <param name="localPath">返回站点相对路径和文件名</param>
    /// <param name="postedFile">单独文件上传流</param>
    /// <returns></returns>
    private bool SaveImg(string name1, string typepath, HttpPostedFile postedFile, out string localPath)
    {
        //HttpFileCollection files = HttpContext.Current.Request.Files;
        System.Text.StringBuilder strMsg = new System.Text.StringBuilder();

        bool fileOk = false;



        //HttpPostedFile postedFile = files[0];

        string fileName, fileExtension;
        fileName = System.IO.Path.GetFileName(postedFile.FileName);
        if (fileName != "")
        {
            fileExtension = System.IO.Path.GetExtension(fileName);
            String[] allowedExtensions = { ".jpg" };
            for (int i = 0; i < allowedExtensions.Length; i++)
            {
                if (fileExtension.ToLower() == allowedExtensions[i])
                {
                    fileOk = true;
                    break;
                }
            }
        }
        if (fileOk)
        {

            //Bitmap bm = new Bitmap(path);
            //本地image文件夹路径
            string sPath = System.Web.HttpContext.Current.Request.MapPath("UpLoadImages\\" + typepath + "\\");
            //文件扩展名
            fileExtension = System.IO.Path.GetExtension(fileName).ToLower();
            //随机文件名
            Random rnd = new Random();
            // string newName = DateTime.Now.ToString().Replace("-", "").Replace(":", "").Replace(" ", "") + rnd.Next(1000).ToString();
            string newName = name1;
            localPath = "UpLoadImages\\" + typepath + "\\" + newName + fileExtension;
            // postedFile.SaveAs(System.Web.HttpContext.Current.Request.MapPath("UpLoadImages/") + newName + fileExtension);

            // Bitmap bmp = new Bitmap(postedFile.InputStream);



            double width = 1024;
            double height = 768;
            //从文件取得图片对象
            System.Drawing.Image image = System.Drawing.Image.FromStream(postedFile.InputStream);
            System.Double NewWidth, NewHeight;

            if (image.Width > image.Height)
            {
                NewWidth = width;
                NewHeight = image.Height * (NewWidth / image.Width);
            }
            else
            {
                NewHeight = height;
                NewWidth = (NewHeight / image.Height) * image.Width;
            }

            if (NewWidth > width)
            {
                NewWidth = width;
            }
            if (NewHeight > height)
            {
                NewHeight = height;
            }

            //取得图片大小
            System.Drawing.Size size = new Size((int)NewWidth, (int)NewHeight);
            //新建一个bmp图片
            System.Drawing.Image bitmap = new System.Drawing.Bitmap(size.Width, size.Height);
            //新建一个画板
            System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(bitmap);
            //设置高质量插值法
            g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;
            //设置高质量,低速度呈现平滑程度
            g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
            //清空一下画布
            g.Clear(System.Drawing.Color.White);
            //在指定位置画图
            g.DrawImage(image, new System.Drawing.Rectangle(0, 0, bitmap.Width, bitmap.Height),
            new System.Drawing.Rectangle(0, 0, image.Width, image.Height),
            System.Drawing.GraphicsUnit.Pixel);

            //保存高清晰度的缩略图
            bitmap.Save(System.Web.HttpContext.Current.Request.MapPath("UpLoadImages\\" + typepath + "\\") + newName + fileExtension, ImageFormat.Jpeg);

            // bmp.Save(System.Web.HttpContext.Current.Request.MapPath("UpLoadImages/") + newName + fileExtension, ImageFormat.Jpeg);


            return true;

        }
        else
        {
            //提示
            localPath = "";
            return false;
        }

    }

    protected void btnUpdate_Click(object sender, EventArgs e)
    {
        save(new Guid(Request["ID"]),false);
    }

    protected void gvSoldiers_RowDeleting(object sender, GridViewDeleteEventArgs e)
    {
        string accountDepartmentID = Yipusoft.Account.BLL.User.GetUser(User.Identity.Name).DepartmentID;

        bool endableDelete = false;
        if (Yipusoft.Account.BLL.User.HasPermission(User.Identity.Name, "203001"))
            endableDelete = true;
        else
            if (Yipusoft.Account.BLL.User.HasPermission(User.Identity.Name, "203008") && accountDepartmentID.Substring(0, 4) == gvSoldiers.DataKeys[e.RowIndex].Values["DepartmentID"].ToString().Substring(0, 4))
                endableDelete = true;
            else
                if (Yipusoft.Account.BLL.User.HasPermission(User.Identity.Name, "203009") && accountDepartmentID == gvSoldiers.DataKeys[e.RowIndex].Values["DepartmentID"].ToString())
                    endableDelete = true;
        if (endableDelete)
        {
            
            TownSoldiersInfo info = TownSoldiers.GetTownSoldiers(new Guid( gvSoldiers.DataKeys[e.RowIndex].Values["SoldierID"].ToString()));
            string name = info.SoldierName;
            info.SoldierID = new Guid(gvSoldiers.DataKeys[e.RowIndex].Values["SoldierID"].ToString());
            info.SetTime=DateTime.Now;
            info.DeleteReason="人工删除";
            info.SetUserName=Yipusoft.Account.BLL.User.GetUser(User.Identity.Name).UserName;
            info.SetAID=User.Identity.Name;
            info.IsDelete = true;
            if (TownSoldiers.Update(info))
            {
                EventLogInfo log = new EventLogInfo();
                log.EventTime = DateTime.Now;
                log.EventType = 1;
                log.EventData = "删除士兵";
                log.ItemID = name;
                log.ItemName = "BasicBase";
                log.ItemFullUrl = "SoldierArchive/NewEmployee.aspx";
                log.CreatedBy = Context.User.Identity.Name;
                log.CreatedTime = DateTime.Now;
                log.UserIP = Request.UserHostAddress;
                EventLog.Insert(log);

                lblInfo.ForeColor = Color.Black;
                lblInfo.Text = "删除成功。";
                BindSoldiers();
            }
            else
            {
                lblInfo.ForeColor = Color.Red;
                lblInfo.Text = "删除失败！";
            }
        }
        else
        {
            lblInfo.ForeColor = Color.Red;
            lblInfo.Text = "您无权删除此兵员记录！";
        }
    }
    protected void btnAutoWrite_Click(object sender, EventArgs e)
    {
        //CardCodeInfo cardCodeInfo = new CardCodeInfo();
        //if (ddlDepartment.SelectedValue.Substring(0, 5) == "13121")
        //{
        //    cardCodeInfo = CardCode.GetCardCodeInfoByDepartmentID("1312100");
        //}
        //else if (ddlDepartment.SelectedValue == "1313100")
        //{
        //    cardCodeInfo = CardCode.GetCardCodeInfoByDepartmentID("1313100");

        //}
        //else
        //{

        //    cardCodeInfo = CardCode.GetCardCodeInfoByDepartmentID(ddlDepartment.SelectedValue.Substring(0, 4) + "000");
        //}
        //if (cardCodeInfo != null)
        //{
        //    int len = cardCodeInfo.StartNum.Length;
        //    Soldier soldier = new Soldier();
        //    for (int i = int.Parse(cardCodeInfo.StartNum); i <= int.Parse(cardCodeInfo.EndNum); i++)
        //    {
        //        string cardID = cardCodeInfo.FrontCode + i.ToString().PadLeft(len, '0');
        //        if (soldier.GetSoldiersCountByWhere("CardID='" + cardID + "' and Left(DepartmentID,4)='" + cardCodeInfo.DepartmentID.Substring(0, 4) + "'") == 0)
        //        {
        //            CardID.Text = cardID;
        //            break;
        //        }

        //    }
        //}
        //else
        //    CardID.Text = "";
    }
    protected void ddlDepartment_SelectedIndexChanged(object sender, EventArgs e)
    {
        DepartmentListBind();
    }
    //void bindSelection()
    //{
    //    if (ddlDepartment.SelectedValue != "")
    //    {
    //        string departmentid = ddlDepartment.SelectedValue;
    //        ddlSection.DataSource = Department.GetList("DepartmentId like '" + departmentid.Substring(0, 4) + "%'");
    //        ddlSection.DataBind();
    //    }
    //    else
    //    {
    //        ddlSection.Items.Clear();
    //    }
    //}
    protected void IsContract_CheckedChanged(object sender, EventArgs e)
    {
        //if (IsContract.Checked)
        //{
        //    Newillpanel.Visible = false;
        //}
        //else
        //{
        //    Newillpanel.Visible = true;
        //}
    }
    protected void ddlSection_SelectedIndexChanged(object sender, EventArgs e)
    {
        BingDDLBasicInfo();
    }
}
